Spring IoC Interview Questions - Set 1

1. What is Inversion of Control (IoC) in Spring?

IoC is a design principle where the control of object creation and dependency management is transferred to the Spring container instead of being managed manually in code.

2. What are the different types of IoC containers in Spring?

Spring provides several types of IoC containers:

3. How do you define a Spring Bean using XML configuration?

You can define a Spring Bean in an XML file as follows:

        <bean id="myBean" class="com.example.MyClass"/>
    

4. How do you define a Spring Bean using Java-based configuration?

Using Java-based configuration with @Configuration and @Bean:

        @Configuration
        public class AppConfig {
            @Bean
            public MyClass myBean() {
                return new MyClass();
            }
        }
    

5. What are the scopes of a Spring Bean?

Spring Bean scopes:

6. How do you configure dependency injection in Spring?

Using XML-based configuration:

        <bean id="service" class="com.example.MyService">
            <constructor-arg ref="repository"/>
        </bean>
    

Using Java-based configuration:

        @Component
        public class MyService {
            private final MyRepository repository;
            @Autowired
            public MyService(MyRepository repository) {
                this.repository = repository;
            }
        }
    

7. What is the difference between @Component, @Service, and @Repository?

8. How do you enable component scanning in Spring?

Using XML configuration:

        <context:component-scan base-package="com.example"/>
    

Using Java-based configuration:

        @Configuration
        @ComponentScan("com.example")
        public class AppConfig {}
    

9. What is the role of @Autowired in Spring?

@Autowired is used to inject dependencies automatically. Example:

        @Component
        public class MyService {
            @Autowired
            private MyRepository repository;
        }
    

10. How do you explicitly define a primary bean in case of multiple candidates?

Using @Primary annotation:

        @Bean
        @Primary
        public MyRepository mainRepository() {
            return new MainRepositoryImpl();
        }
    


    

Spring IoC Interview Questions - Set 2

11. What is the difference between constructor injection and setter injection?

Constructor injection is used when dependencies are passed via the constructor, while setter injection assigns dependencies via setter methods.

Example of constructor injection:

        public class MyService {
            private final MyRepository repository;
            public MyService(MyRepository repository) {
                this.repository = repository;
            }
        }
    

Example of setter injection:

        public class MyService {
            private MyRepository repository;
            public void setRepository(MyRepository repository) {
                this.repository = repository;
            }
        }
    

12. How can you define bean dependencies in Spring?

Using XML-based configuration:

        <bean id="myService" class="com.example.MyService">
            <constructor-arg ref="myRepository"/>
        </bean>
    

13. What is @Qualifier used for in Spring?

@Qualifier is used to specify which bean to inject when multiple beans of the same type exist.

        @Component
        public class MyService {
            @Autowired
            @Qualifier("specialRepository")
            private MyRepository repository;
        }
    

14. What is a Spring Bean lifecycle?

A Spring Bean lifecycle includes creation, initialization, usage, and destruction.

15. How do you define an initialization and destruction method in Spring?

Using XML configuration:

        <bean id="myBean" class="com.example.MyClass" init-method="init" destroy-method="cleanup"/>
    

Using annotations:

        public class MyClass {
            @PostConstruct
            public void init() {
                // Initialization logic
            }
            @PreDestroy
            public void cleanup() {
                // Cleanup logic
            }
        }
    

16. How does Spring handle circular dependencies?

Spring can handle circular dependencies by using setter injection instead of constructor injection.

17. What is Lazy Initialization in Spring?

Lazy initialization delays bean creation until it is needed.

        @Bean
        @Lazy
        public MyService myService() {
            return new MyService();
        }
    

18. What is the difference between ApplicationContext and BeanFactory?

BeanFactory is a lower-level container, whereas ApplicationContext provides more features like event propagation and internationalization.

19. How do you define a prototype-scoped bean in Spring?

Using XML configuration:

        <bean id="myBean" class="com.example.MyClass" scope="prototype"/>
    

Using Java configuration:

        @Bean
        @Scope("prototype")
        public MyClass myBean() {
            return new MyClass();
        }
    

20. What are Spring Profiles?

Spring Profiles allow beans to be registered conditionally based on the environment.

        @Profile("dev")
        @Bean
        public DataSource devDataSource() {
            return new HikariDataSource();
        }
    


Spring IoC Interview Questions - Set 3

21. What is the difference between @Bean and @Component?

@Bean is used in Java-based configuration to explicitly declare a Spring bean, whereas @Component is used for automatic component scanning.

        @Configuration
        public class AppConfig {
            @Bean
            public MyService myService() {
                return new MyService();
            }
        }
    

22. How do you enable annotation-based configuration in Spring?

Using Java-based configuration:

        @Configuration
        @ComponentScan("com.example")
        public class AppConfig {}
    

23. What is the purpose of @PostConstruct and @PreDestroy?

@PostConstruct is used to execute initialization logic after dependency injection, and @PreDestroy is used for cleanup before a bean is destroyed.

        public class MyBean {
            @PostConstruct
            public void init() {
                // Initialization logic
            }
            @PreDestroy
            public void cleanup() {
                // Cleanup logic
            }
        }
    

24. What is the default scope of a Spring bean?

The default scope of a Spring bean is singleton.

25. How do you create an ApplicationContext in Spring?

You can create an ApplicationContext using:

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    

26. What are Factory Beans in Spring?

Factory Beans are special beans that produce other beans dynamically.

        public class MyFactoryBean implements FactoryBean {
            @Override
            public MyBean getObject() throws Exception {
                return new MyBean();
            }
            @Override
            public Class getObjectType() {
                return MyBean.class;
            }
        }
    

27. What is Spring Expression Language (SpEL)?

SpEL allows querying and manipulating objects dynamically in Spring.

        @Value("#{systemProperties['user.name']}")
        private String userName;
    

28. How do you handle property files in Spring?

Using @PropertySource:

        @Configuration
        @PropertySource("classpath:app.properties")
        public class AppConfig {}
    

29. How can you access a property value in Spring?

Using @Value annotation:

        @Value("${app.name}")
        private String appName;
    

30. What is @DependsOn in Spring?

@DependsOn forces bean initialization order.

        @Bean
        @DependsOn("otherBean")
        public MyBean myBean() {
            return new MyBean();
        }
    


    

Spring IoC Interview Questions - Set 4

31. What is the role of @Autowired in Spring?

@Autowired is used for automatic dependency injection in Spring.

        @Component
        public class MyService {
            @Autowired
            private MyRepository repository;
        }
    

32. Can @Autowired be used on constructors?

Yes, @Autowired can be used on constructors for dependency injection.

        @Component
        public class MyService {
            private final MyRepository repository;
            @Autowired
            public MyService(MyRepository repository) {
                this.repository = repository;
            }
        }
    

33. What is the difference between @Autowired and @Inject?

@Autowired is Spring-specific, while @Inject is a standard Java annotation from JSR-330.

34. What is the difference between @Autowired and @Resource?

@Autowired is Spring-specific, whereas @Resource is part of Java EE and allows specifying bean names.

35. How do you resolve conflicts when multiple beans qualify for @Autowired?

Use @Qualifier to specify the exact bean.

        @Component
        public class MyService {
            @Autowired
            @Qualifier("specialRepository")
            private MyRepository repository;
        }
    

36. What happens if a required dependency is missing for @Autowired?

Spring throws a NoSuchBeanDefinitionException unless @Autowired(required = false) is specified.

37. How can you inject values from properties files using @Value?

Use @Value to inject values from application.properties.

        @Value("${app.name}")
        private String appName;
    

38. What is the difference between prototype and singleton scope?

Singleton creates a single instance for the container, while prototype creates a new instance each time it is requested.

39. How do you configure component scanning in Spring?

Use @ComponentScan in Java configuration.

        @Configuration
        @ComponentScan("com.example")
        public class AppConfig {}
    

40. How do you define primary beans in Spring?

Use @Primary to mark a bean as the default when multiple beans exist.

        @Bean
        @Primary
        public MyRepository defaultRepository() {
            return new DefaultRepository();
        }
    

 

Spring IoC Interview Questions - Set 5

41. What is the default scope of a Spring bean?

The default scope of a Spring bean is singleton.

42. How do you define a prototype-scoped bean?

Use @Scope("prototype") on the bean definition.

        @Bean
        @Scope("prototype")
        public MyBean myPrototypeBean() {
            return new MyBean();
        }
    

43. Can you inject a prototype bean into a singleton bean?

Yes, but it requires using ObjectFactory or Provider to get a new instance each time.

        @Component
        public class SingletonBean {
            @Autowired
            private ObjectFactory prototypeBeanFactory;
            
            public PrototypeBean getPrototypeInstance() {
                return prototypeBeanFactory.getObject();
            }
        }
    

44. What is the difference between field injection and constructor injection?

Field injection uses @Autowired on fields, while constructor injection provides better testability and immutability.

45. How do you specify a bean name in Spring?

Use the name attribute in @Component or @Bean annotations.

        @Component("myCustomBean")
        public class MyBean {}
    

46. What is @Lazy annotation in Spring?

@Lazy delays bean initialization until it is first requested.

        @Bean
        @Lazy
        public ExpensiveBean expensiveBean() {
            return new ExpensiveBean();
        }
    

47. How do you retrieve a bean by name in Spring?

Use ApplicationContext’s getBean() method.

        MyBean myBean = applicationContext.getBean("myBean", MyBean.class);
    

48. What is the purpose of @Configuration annotation?

@Configuration is used to define Java-based configuration for Spring beans.

49. How do you enable annotation-based configuration in Spring?

Use @ComponentScan and @EnableAutoConfiguration.

        @Configuration
        @ComponentScan("com.example")
        @EnableAutoConfiguration
        public class AppConfig {}
    

50. What is the use of @DependsOn annotation?

@DependsOn forces a bean to be initialized after another specified bean.

        @Bean
        @DependsOn("otherBean")
        public MyBean myBean() {
            return new MyBean();
        }
    

 

Spring IoC Interview Questions - Set 6

51. What is the difference between @Bean and @Component?

@Bean is used in Java-based configuration classes, while @Component is used for component scanning.

52. What is the use of @Primary annotation?

@Primary is used to indicate the primary bean when multiple beans of the same type exist.

        @Bean
        @Primary
        public MyBean myPrimaryBean() {
            return new MyBean();
        }
    

53. How do you handle multiple beans of the same type in Spring?

Use @Primary, @Qualifier, or manually retrieve beans from the context.

54. What is the purpose of @PostConstruct and @PreDestroy annotations?

@PostConstruct is used for initialization logic, and @PreDestroy is used for cleanup.

        @Component
        public class MyBean {
            @PostConstruct
            public void init() {
                System.out.println("Bean initialized");
            }
            
            @PreDestroy
            public void destroy() {
                System.out.println("Bean destroyed");
            }
        }
    

55. How do you load external properties in Spring?

Use @PropertySource and Environment.

        @Configuration
        @PropertySource("classpath:application.properties")
        public class AppConfig {
            @Autowired
            private Environment env;
        }
    

56. What is the use of @Value annotation?

@Value is used to inject values from properties files.

        @Value("${app.name}")
        private String appName;
    

57. How do you create a custom scope in Spring?

Implement the Scope interface and register it with the ConfigurableBeanFactory.

58. What is the default order of bean initialization in Spring?

By default, singleton beans are initialized in the order they are declared, but dependencies are resolved first.

59. What is circular dependency in Spring, and how do you resolve it?

A circular dependency occurs when two beans depend on each other. It can be resolved using @Lazy, constructor injection, or setter injection.

60. How do you enable JSR-330 annotations in Spring?

Use @Inject and @Named, and include the relevant dependency in the classpath.

        @Named
        public class MyService {}
    

 

Spring IoC Interview Questions - Set 7

61. What is the role of BeanFactoryPostProcessor in Spring?

It allows modifying bean definitions before they are instantiated.

62. How does the PropertySourcesPlaceholderConfigurer work?

It replaces placeholders in bean definitions with values from property files.

63. What is the difference between @Resource and @Autowired?

@Resource is part of JSR-250 and allows specifying a bean name, whereas @Autowired is Spring-specific.

64. How do you configure a bean lifecycle in Spring?

Use @PostConstruct, @PreDestroy, or define init-method and destroy-method in XML.

65. What is the use of @DependsOn annotation?

It ensures a bean is initialized only after specific dependent beans.

        @Bean
        @DependsOn("dataSource")
        public MyService myService() {
            return new MyService();
        }
    

66. What is the significance of AnnotationConfigApplicationContext?

It is used to register and scan Java-based configuration classes.

67. How does Spring handle prototype beans?

Prototype beans are created each time they are requested from the container.

68. What is the use of @Lazy annotation?

It delays the initialization of a bean until it is requested.

69. How can you define a factory method for a bean?

Use a static factory method inside a configuration class.

        @Bean
        public static MyBean createBean() {
            return new MyBean();
        }
    

70. How do you define a conditional bean in Spring?

Use the @Conditional annotation with a custom condition class.

 

Spring IoC Interview Questions - Set 8

71. What is the difference between @Conditional and @Profile?

@Conditional allows defining conditions for bean creation, whereas @Profile enables environment-specific beans.

72. How do you create a custom @Conditional annotation?

Implement the Condition interface and override the matches method.

        public class MyCondition implements Condition {
            @Override
            public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
                return context.getEnvironment().containsProperty("my.property");
            }
        }
    

73. How does Spring handle method injection?

By using lookup methods or ObjectFactory.

74. What is the purpose of AbstractApplicationContext?

It provides lifecycle management methods for application contexts.

75. How do you enable component scanning in Spring?

Use @ComponentScan in Java-based configurations.

        @Configuration
        @ComponentScan("com.example")
        public class AppConfig {}
    

76. What are ApplicationContextAware and BeanFactoryAware?

They allow beans to access ApplicationContext and BeanFactory, respectively.

77. How does Spring handle multiple configurations?

Use @Import to import additional configuration classes.

78. What is the role of DelegatingFilterProxy in Spring?

It allows integrating Spring-managed beans with Servlet filters.

79. What are the types of Bean Scopes available in Spring?

Singleton, Prototype, Request, Session, Application, and WebSocket.

80. What is the difference between FactoryBean and a regular Bean?

FactoryBean creates objects dynamically, while a regular Bean is directly managed by the IoC container.

 

Spring IoC Interview Questions - Set 9

81. What is the difference between @Primary and @Qualifier?

@Primary gives higher preference to a bean, whereas @Qualifier is used to specify a particular bean explicitly.

82. How do you configure a Spring bean programmatically?

Use the registerBean method in ConfigurableApplicationContext.

        context.registerBean(MyBean.class);
    

83. What is the purpose of the BeanDefinitionRegistry?

It is used to dynamically register bean definitions.

84. How does Spring handle circular dependencies?

By using proxy beans or constructor injection with @Lazy.

85. What is the use of @Scope annotation?

It defines the scope of a bean, e.g., singleton, prototype.

86. How do you create a BeanFactoryPostProcessor?

Implement the BeanFactoryPostProcessor interface and override postProcessBeanFactory.

        public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                // Modify bean definitions
            }
        }
    

87. What is the difference between BeanFactory and ApplicationContext?

ApplicationContext provides more features like event propagation and declarative bean creation.

88. What is the role of the SmartInitializingSingleton interface?

It ensures that singleton beans are initialized after the complete bean creation process.

89. How do you register a shutdown hook in Spring?

Use registerShutdownHook() on the application context.

        context.registerShutdownHook();
    

90. How does Spring support JSR-330 annotations?

By enabling component scanning and using @Inject instead of @Autowired.

 

Spring IoC Interview Questions - Set 10

91. What is the use of the @DependsOn annotation in Spring?

It specifies that a bean should be initialized after another bean.

92. How do you refresh an ApplicationContext in Spring?

By calling the refresh() method on ConfigurableApplicationContext.

        ((ConfigurableApplicationContext) context).refresh();
    

93. What is the purpose of the ConfigurableApplicationContext interface?

It provides additional lifecycle methods such as refresh and close.

94. How can you create a lazy-initialized bean in Spring?

By using the @Lazy annotation.

        @Bean
        @Lazy
        public MyBean myBean() {
            return new MyBean();
        }
    

95. What is the difference between @PostConstruct and InitializingBean?

@PostConstruct is a JSR-250 annotation, whereas InitializingBean requires implementing an interface.

96. What is the use of @Lookup annotation in Spring?

It enables method injection by dynamically returning a bean instance.

97. How can you dynamically create and register a bean at runtime in Spring?

By using BeanDefinitionRegistry.

        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(MyBean.class);
        registry.registerBeanDefinition("myBean", beanDefinition);
    

98. What is the purpose of @EventListener in Spring?

It listens to application events published in the Spring context.

        @EventListener
        public void handleEvent(MyEvent event) {
            System.out.println("Event received: " + event.getMessage());
        }
    

99. How does Spring handle internationalization (i18n)?

By using MessageSource to load messages from properties files.

100. What is the role of @EnableAspectJAutoProxy?

It enables support for handling components marked with @Aspect annotations.

 

Spring IoC Interview Questions - Set 11

101. What is the purpose of the @Primary annotation in Spring?

It marks a bean as the primary candidate when multiple beans of the same type exist.

102. How do you create a prototype bean in Spring?

By using the @Scope("prototype") annotation.

        @Bean
        @Scope("prototype")
        public MyBean myPrototypeBean() {
            return new MyBean();
        }
    

103. What is the difference between ApplicationContext and BeanFactory?

ApplicationContext provides more features like event propagation, declarative mechanisms, and AOP support, whereas BeanFactory is a simpler container.

104. How do you programmatically register a bean in Spring?

By using ConfigurableApplicationContext and BeanDefinitionRegistry.

        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(MyBean.class);
        registry.registerBeanDefinition("myBean", beanDefinition);
    

105. What is the role of @Conditional in Spring?

It allows bean creation based on specified conditions.

106. How can you inject a bean into a static field in Spring?

By using a setter method and marking it with @Autowired.

107. What is the purpose of @EnableAutoConfiguration?

It enables Spring Boot to automatically configure components based on classpath dependencies.

108. How can you access an ApplicationContext from a bean?

By implementing ApplicationContextAware.

        @Component
        public class MyBean implements ApplicationContextAware {
            private ApplicationContext context;

            @Override
            public void setApplicationContext(ApplicationContext applicationContext) {
                this.context = applicationContext;
            }
        }
    

109. What is the difference between @Component and @Service?

@Service is a specialization of @Component, used for service layer beans.

110. How do you disable a Spring Boot auto-configuration?

By using @EnableAutoConfiguration(exclude = {SomeAutoConfiguration.class}).

 

 

Spring IoC Interview Questions - Set 12

111. What is the use of the @Transactional annotation in Spring?

It manages transactions automatically, ensuring consistency and rollback on failure.

112. How does Spring handle circular dependencies?

Spring can resolve circular dependencies using proxies, but constructor-based dependencies may fail.

113. What is the role of the @SessionScope annotation?

It defines a bean's scope to be limited to an HTTP session.

114. How can you customize a Spring bean's initialization?

By using the @PostConstruct annotation or implementing InitializingBean.

115. What is a FactoryBean in Spring?

A special bean that returns an instance of another object, not itself.

116. How do you define a custom scope in Spring?

By implementing the Scope interface and registering it with ConfigurableBeanFactory.

117. What is the difference between @RestController and @Controller?

@RestController is a combination of @Controller and @ResponseBody, used for REST APIs.

118. How do you enable CORS in a Spring Boot application?

By using @CrossOrigin at the controller level or configuring WebMvcConfigurer.

119. What is the purpose of @EnableWebMvc?

It enables default Spring MVC configurations and components.

120. How do you inject a value from application.properties in Spring?

By using the @Value annotation.

        @Value("${app.name}")
        private String appName;